from flask import Blueprint, request

from controllers import R
from mauth import HasPerm
from models.schema import Schema
from services.schema_service import SchemaService
from validators import BasePageForm
from validators.id_validator import IdForm, IdsForm
from validators.schema_validator import SchemaForm

# 声明一个蓝图
schema = Blueprint("schema", __name__, url_prefix="/dev/schema")

# 声明一个数据模型业务服务
schema_service = SchemaService(model=Schema)


@schema.route("/detail", methods=["POST"])
@HasPerm(access="dev:schema:detail", name="通过id获取数据模型信息")
def schema_detail():
    """
    通过id获取数据模型信息
    :return:
    """
    form = IdForm()
    form.validate_for_api()
    # 可通过form.data获取所有提交参数
    # 或者直接拿id值 id=form.id.data
    # u = Schema.query.filter_by(id=form.id.data).first()
    # 通过主键查询
    u = schema_service.detail(form)
    if u is not None:
        return R.data(u)
    else:
        return R.fail("该记录不存在")


@schema.route("/page", methods=["POST"])
@HasPerm(access="dev:schema:page", name="分页查询数据模型列表")
def schema_page():
    """
    分页查询数据模型列表
    :return:
    """
    form = BasePageForm()
    form.validate_for_api()
    return R.data(schema_service.page(form))


@schema.route("/save", methods=["POST"])
@HasPerm(access="dev:schema:save", name="添加数据模型")
def schema_save():
    """
    添加数据模型
    :return:
    """
    form = SchemaForm()
    form.validate_for_api()
    # 可通过form.data获取所有提交参数
    # print(form.data)
    schema_service.save(form)
    return R.success("添加数据模型成功")


@schema.route("/update", methods=["POST"])
@HasPerm(access="dev:schema:update", name="修改数据模型")
def schema_update():
    """
    修改数据模型
    :return:
    """
    form = SchemaForm()
    form.validate_for_api()
    # 可通过form.data获取所有提交参数
    # print(form.data)
    schema_service.update(form)
    return R.success("修改数据模型成功")


@schema.route("/getByTableName", methods=["GET"])
def schema_get_by_table_name():
    """
    根据表名称获取数据模型
    :return:
    """

    return R.data(schema_service.get_by_table_name(request.args.get("tableName")))


@schema.route("/remove", methods=["POST"])
def schema_remove():
    """
    删除数据模型
    :return:
    """
    form = IdsForm()
    form.validate_for_api()
    # 可通过form.data获取所有提交参数
    # print(form.data)
    schema_service.remove(form)
    return R.success("删除数据模型成功")
